package com.ztz.musicappdemo.activity;

import android.Manifest;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.ztz.musicappdemo.ActivityCollector;
import com.ztz.musicappdemo.MyService;
import com.ztz.musicappdemo.R;
import com.ztz.musicappdemo.adapter.MusicLVadapter;
import com.ztz.musicappdemo.bean.Music;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseActivity
        implements NavigationView.OnNavigationItemSelectedListener{//侧滑栏
    ListView lv_musiclist;
    MusicLVadapter musicLVadapter;
    List<Music> musicList=new ArrayList<>();
    MediaPlayer mp;
   public static SeekBar seekBar;
    Button btn_pause;
    Button btn_stop;
    TextView nav_Name;
//    int progress=0;

    MyService.MusicBinder musicBinder;
    public static Handler handler=new Handler(){
        //处理Service传来的信息;
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    //修改进度;
                    int duration=msg.arg1;
                    int progress=msg.arg2;
                    seekBar.setMax(duration);
                    seekBar.setProgress(progress);
            }
        }
    };
    public ServiceConnection connection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            musicBinder= (MyService.MusicBinder) service;

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lv_musiclist=(ListView)findViewById(R.id.lvMusicList);
        seekBar=(SeekBar)findViewById(R.id.seek_bar);

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                musicBinder.seekWait();
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int progress=seekBar.getProgress();
                musicBinder.seekTo(progress);
                musicBinder.seekNotify();
            }
        });
        btn_pause=(Button)findViewById(R.id.btn_pause);
        btn_stop=(Button)findViewById(R.id.btn_stop);
        Intent intent=new Intent(this,MyService.class);
        startService(intent);
        bindService(intent,connection,BIND_AUTO_CREATE);
//        musicList.add(new Music(1,"李白","李荣浩",null,"",0,0,0));
//        musicList.add(new Music(2,"老街","李荣浩",null,"",0,0,0));
//        musicList.add(new Music(2,"七里香","周杰伦",null,"",0,0,0));
        musicLVadapter=new MusicLVadapter(this,musicList);
        lv_musiclist.setAdapter(musicLVadapter);
        lv_musiclist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                    musicBinder.start();
                }
//               try{
//                   if(mp.isPlaying()){
//                       mp.reset();
//                   }
//                   mp.setDataSource(musicList.get(position).getUrl());
//                   mp.prepare();
//                   mp.start();
//
//               }catch (Exception e){
//                   e.printStackTrace();
//               }

//                Toast.makeText(MainActivity.this,""+musicList.get(position).getTitle(),Toast.LENGTH_SHORT).show();

            }
        });

        if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
            //申请权限
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},1);
        }else {
            initMusicList();//没申请权限
        }
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);//标题按钮
        setSupportActionBar(toolbar);

//        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);//浮动按钮
//        fab.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
//                        .setAction("Action", null).show();
//            }
//        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        nav_Name=(TextView)navigationView.getHeaderView(0).findViewById(R.id.nav_name);
        nav_Name.setText("签名");
        btn_pause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                musicBinder.pause();
            }
        });
        btn_stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                musicBinder.stop();
            }
        });
    }

//    @Override
//    protected void onDestroy() {
//        super.onDestroy();
//        mp.stop();
//
//    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case 1:
                if(grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED){
                    initMusicList();
                }else {
                    Toast.makeText(this, "用户拒绝", Toast.LENGTH_SHORT).show();
                }
        }
    }

    private void initMusicList() {
        //初始化音乐列表，读本的文件
       Cursor cursor=getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,null,null,null,MediaStore.Audio.Media.DEFAULT_SORT_ORDER);

        while (cursor.moveToNext()) {
            //循环Music保存到list中
            int id = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID));
            String title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
            String album = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
            String artist = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
            String url = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
            Log.d("url","url"+url);
            int duration = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));
            int size = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE));

            musicList.add(new Music(id,title,artist,album,url,duration,size,cursor.getPosition()));

        }

        musicLVadapter.notifyDataSetChanged();
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {

            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_UserInfo_Manager) {
            Intent intent=new Intent(MainActivity.this,UserInfoManageActivity.class);
            startActivity(intent);
            // Handle the camera action
        } else if (id == R.id.nav_User_Change) {
            Intent intent=new Intent(MainActivity.this,UserChangeActivity.class);
            intent.putExtra("userName","admin");
            intent.putExtra("password","123456");
            startActivity(intent);

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_quit) {
            ActivityCollector.finishAll();
            Intent intent=new Intent(MainActivity.this,LoginActivity.class);
            startActivity(intent);


        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}
